<template>
  <div class="tenant-wrapper">
    <div class="tenant-btns">
      <el-button type="primary" @click="toggleDialog('add')">新增企业</el-button>
    </div>
    <el-table v-loading="listLoading" :data="listData" border fit highlight-current-row>
      <el-table-column prop="name" label="用工单位名称"> </el-table-column>
      <el-table-column prop="name" label="经办人" width="120">
        <template slot-scope="scope">
          {{ scope.row.enterpriseOperator ? scope.row.enterpriseOperator.name : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="mobile" label="经办人电话" width="120">
        <template slot-scope="scope">
          {{ scope.row.enterpriseOperator ? scope.row.enterpriseOperator.mobile : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="address" label="企业注册地址"> </el-table-column>
      <el-table-column prop="createOn" label="创建日期" width="180">
        <template slot-scope="scope">
          <i class="el-icon-time" style="marginright: 4px" />
          <span>{{ scope.row.createdOn | dateFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="latestFlowStatus" label="状态" width="90">
        <template slot-scope="scope">
          <span>{{ scope.row.latestFlowStatus | statusFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="toggleDialog('mod', scope.row)">编辑</el-button>
          <el-button
            v-if="scope.row.latestFlowStatus === 'UNDISTURBED'"
            type="text"
            size="small"
            @click="clickCreateContract(scope.row)"
            >发起合同</el-button
          >
          <el-popconfirm title="确定删除吗？" @confirm="handleClickDelete(scope.row)">
            <el-button slot="reference" type="text" size="small" style="color: red; marginLeft: 8px">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="tenant-page">
      <el-pagination
        small
        layout="prev, pager, next, total, sizes, jumper"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20, 50, 100]"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
      >
      </el-pagination>
    </div>

    <!-- 企业新增/修改 -->
    <el-dialog :title="dialogTitle" :visible.sync="tenantVisible" :close-on-click-modal="false" width="500px">
      <el-form
        :model="tenantForm"
        ref="tenantForm"
        :rules="addRules"
        label-width="110px"
        size="small"
        label-position="left"
        class="tenant-form"
      >
        <el-form-item label="企业名称" prop="name" required>
          <el-input v-model="tenantForm.name"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="agentName" required>
          <el-input v-model="tenantForm.agentName"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="agentMobile" required>
          <el-input v-model="tenantForm.agentMobile"></el-input>
        </el-form-item>
        <el-form-item label="企业注册地址" prop="address">
          <el-input v-model="tenantForm.address"></el-input>
        </el-form-item>
        <el-form-item class="form-btns">
          <el-button @click="resetForm('tenantForm')">取消</el-button>
          <el-button type="primary" @click="submitForm('tenantForm')">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 发起劳务派遣协议 -->
    <el-dialog title="发起劳务派遣协议" :visible.sync="agreementVisible" :close-on-click-modal="false" :destroy-on-close="true" :before-close="onDialogClose" top="6vh">
      <!-- 发起合同弹框 -->
      <contractCreate ref="createRef" :templateType="1" :templateList="templateList" :currentRow="currentRow" :close="cancelForm"></contractCreate>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment';
import { getTenantList, addTenant, updateTenant, deleteTenant } from '@common/api/tenant';
import { getTemplateList } from '@common/api/template';
import { TENANT_STATUS } from '@common/consts/status';
import { validMobile } from '@common/utils/validate';
import contractCreate from '../components/contractCreate';

export default {
  name: 'undisturbed',
  components: {
    contractCreate,
  },
  data() {
    return {
      listLoading: false,
      listData: [],
      pageSize: 10,
      currentPage: 1,
      total: 0,
      selectedData: [],
      tenantVisible: false,
      tenantForm: {
        name: '',
        agentName: '',
        agentMobile: '',
        address: '',
      },
      addRules: {
        name: [
          { required: true, message: '请输入企业名称', trigger: 'change' },
          { required: true, message: '请输入企业名称', trigger: 'blur' },
        ],
        agentName: [
          { required: true, message: '请输入经办人', trigger: 'change' },
          { required: true, message: '请输入经办人', trigger: 'blur' },
        ],
        agentMobile: [
          { required: true, message: '请输入联系电话', trigger: 'change' },
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { validator: validMobile, message: '请输入正确的手机号' },
        ],
      },
      dialogTitle: '新增企业',
      type: 'add',
      currentRow: {},
      agreementVisible: false,
      templateList: [],
    };
  },
  filters: {
    dateFilter(time) {
      if (String(time).length === 13) {
        return moment(time).format('YYYY-MM-DD HH:mm');
      }
      if (String(time).length === 10) {
        return moment(time * 1000).format('YYYY-MM-DD HH:mm');
      }
      return '';
    },
    statusFilter(status) {
      return status ? TENANT_STATUS[status] : '';
    },
  },
  // watch: {
  //   agreementVisible(val) {
  //     if (!val) {
  //       this.$refs.createRef.resetCreate(); // 重置数据
  //       this.currentRow = {};
  //     }
  //   },
  // },
  created() {
    this.getList();
    this.getTemplateList();
  },
  methods: {
    // 获取列表数据
    async getList() {
      this.listLoading = true;
      const params = {
        status: 'UNDISTURBED',
        limit: this.pageSize,
        offset: (this.currentPage - 1) * this.pageSize,
      };
      const response = await getTenantList(params);
      if (response?.data?.tenants?.length) {
        this.listData = response?.data?.tenants;
      } else {
        this.listData = [];
      }
      this.total = response?.data?.totalCount || 0;
      this.listLoading = false;
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },

    // 新增/编辑 企业
    toggleDialog(type, data) {
      this.type = type;
      this.dialogTitle = type === 'add' ? '新增企业' : '编辑企业';
      // console.log('type', type, data);
      if (type === 'mod') {
        this.currentRow = data;
        const temp = {
          name: data?.name,
          agentName: data?.enterpriseOperator?.name,
          agentMobile: data?.enterpriseOperator?.mobile,
          address: data?.address,
        };
        this.$set(this, 'tenantForm', temp);
      } else {
        this.$refs?.tenantForm?.resetFields();
        this.$set(this, 'tenantForm', { name: '', agentName: '', agentMobile: '', address: '' });
      }
      this.tenantVisible = true;
    },
    // 保存 用工企业
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // console.log('保存数据', this.tenantForm);
          const { name, address, agentMobile, agentName } = this.tenantForm;
          const params = {
            name,
            enterpriseOperator: {
              name: agentName,
              mobile: agentMobile,
            },
            address,
          };
          let apiName = '';
          if (this.type === 'add') {
            apiName = addTenant;
            params.latestFlowStatus = 'UNDISTURBED'; // 新增企业的时候默认是未发起状态
          } else if (this.type === 'mod') {
            apiName = updateTenant;
            params.id = this.currentRow.id;
          }
          apiName(params).then(res => {
            // console.log('Tenant====', res);
            if (res?.code === 20000) {
              this.currentRow = res?.data;
              this.tenantVisible = false;
              if (this.type === 'add') {
                this.$confirm('添加用工企业成功', '提示', {
                  confirmButtonText: '发起劳动派遣协议',
                  cancelButtonText: '继续添加',
                  distinguishCancelAndClose: true,
                })
                  .then(() => {
                    // 发起劳动派遣协议
                    this.clickCreateContract(this.currentRow);
                  })
                  .catch(action => {
                    // 继续添加
                    if (action === 'cancel') {
                      this.toggleDialog('add');
                    }
                  });
              } else if (this.type === 'mod') {
                this.$message({
                  message: res?.message,
                  type: 'success',
                });
              }
              this.getList();
            } else {
              this.tenantVisible = false;
              this.$message({
                message: res?.message,
                type: 'warning',
              });
            }
          });
        }
      });
    },
    // 取消
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$set(this, 'tenantForm', { name: '', agentName: '', agentMobile: '', address: '' });
      this.tenantVisible = false;
    },
    // 删除
    handleClickDelete(data) {
      // console.log('handleClickDelete====', data);
      deleteTenant({ id: data.id }).then(res => {
        if (res?.code === 20000) {
          this.$message({
            message: res?.message,
            type: 'success',
          });
          this.getList();
        } else {
          this.$message({
            message: res?.message,
            type: 'warning',
          });
        }
      });
    },
    // 点击 发起合同
    clickCreateContract(data) {
      this.currentRow = data;
      this.agreementVisible = true;
    },
    // 取消
    cancelForm() {
      this.agreementVisible = false;
      this.$refs.createRef.resetCreate(); // 重置数据
    },
    // 获取模板列表
    getTemplateList() {
      const params = {
        withPreviewUrl: true, // 是否获取模板预览链接
        templateName: '',
        limit: 100,
        offset: 0,
        // QueryAllComponents: false, // 是否返回所有组件信息。默认false，只返回发起方控件；true，返回所有签署方控件
        // ContentType: 0, // 查询内容：0-模板列表及详情（默认），1-仅模板列表
        tenantTemplateType: 1,
      };
      getTemplateList(params).then(response => {
        if (response?.data?.Templates?.length) {
          this.templateList = response?.data?.Templates;
        } else {
          this.templateList = [];
        }
      });
    },
    onDialogClose() {
      this.agreementVisible = false;
      this.$refs.createRef.resetCreate(); // 重置数据
      this.currentRow = {};
      this.getList();
    },
  },
};
</script>

<style lang="scss" scoped>
.tenant-wrapper {
  padding: 20px;
  .tenant-btns {
    margin-bottom: 20px;
  }
  .tenant-form {
    .form-btns {
      text-align: right;
      margin-top: 20px;
    }
  }
  .tenant-page {
    position: relative;
    text-align: right;
    margin-top: 20px;
    .el-pagination {
      display: inline-block;
    }
  }
}
</style>
